package com.itheima.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.Code;
import com.itheima.domain.Result;
import com.itheima.domain.User;
import com.itheima.exception.BusinessException;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping
    public Result findAll() {
       // int i=1/0;
        List<User> list = userService.findAll();
        return list != null && list.size() > 0 ?
                new Result(Code.QUERY_OK, "查询所有信息成功", list) :
                new Result(Code.QUERY_FAIL, "查询所有信息失败");
    }

    /**
     * 分页查询
     */
    @GetMapping("/{currentPage}/{pageSize}")
    public Result findByPage(@PathVariable Integer currentPage, @PathVariable Integer pageSize) {

        if(currentPage<0 || pageSize<0){
            throw new BusinessException("当前页或者每页条数必须大于0");
        }


        PageInfo<User> pageInfo = userService.findByPage(currentPage, pageSize);
        return pageInfo.getSize() > 0 ?
                new Result(Code.QUERY_OK, "分页查询成功", pageInfo) :
                new Result(Code.QUERY_FAIL, "分页查询失败");

    }

    /**
     * 根据id查询
     */
    @GetMapping("/{id}")
    public Result findById(@PathVariable Integer id) {
        User user = userService.findById(id);
        return user != null ?
                new Result(Code.QUERY_OK, "根据id查询用户成功", user) :
                new Result(Code.QUERY_FAIL, "根据id查询用户失败");

    }

    /**
     * 保存
     */
    @PostMapping
    public Result save(@RequestBody User user) {
        int count = userService.save(user);
        return count > 0 ?
                new Result(Code.SAVE_OK, "保存用户成功") : new Result(Code.SAVE_FAIL, "保存用户失败");

    }

    @PutMapping
    public Result update(@RequestBody User user) {
        int count = userService.update(user);
        return count > 0 ?
                new Result(Code.UPDATE_OK, "修改用户成功") : new Result(Code.UPDATE_FAIL, "修改用户失败");
    }

    /**
     * 根据id删除用户信息
     *
     * @param id 要删除的用户id
     * @return 影响的行数
     * http://localhost:8080/springmvc_03_ssm/user/1 + delete请求
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        int count = userService.delete(id);
        return count > 0 ?
                new Result(Code.DELETE_OK, "删除用户成功") : new Result(Code.DELETE_FAIL, "删除用户失败");
    }

    @PostMapping("/login")
    public Result login(String username, String password, HttpSession session) {
        User user = userService.login(username, password);
        if (user != null) {
            session.setAttribute("user", user);
        }
        return user != null ?
                new Result(Code.LOGIN_OK, "登录成功") : new Result(Code.LOGIN_FAIL, "登录失败");

    }


}
